<script setup>
import { ref, onMounted } from 'vue'
import { gotoPath } from '@renderer/api'
import { useRoute } from 'vue-router'

const users = ref([])
const { ipcRenderer } = window.electron

onMounted(() => {
  console.log('Users mounted')
  ipcRenderer.invoke('getAllUser', { msg: '查询所有用户' }).then((result) => {
      users.value = JSON.parse(result)
    }).catch((error) => {
      console.error('Error fetching users:', error)
      users.value = [] // 设置为空数组以防后续渲染出错
    })
})

const route = useRoute()
const winId = ref(route.query.winId)
const closeWindow = () => {
  ipcRenderer.send('window-close', { winId: winId.value })
}

// 添加用户方法
const addUser = () => {
  // 这里可以打开一个新窗口或对话框来添加用户
  gotoPath('/user/add')
}

// 编辑用户方法
const editUser = (row) => {
  // 这里可以打开一个新窗口或对话框来编辑用户
  gotoPath(`/user/edit?id=${row.id}`)
}

// 删除用户方法
const removeUser = async (id) => {
  try {
    await ipcRenderer.invoke('removeUser', { id })
    // 重新加载用户列表
    const result = await ipcRenderer.invoke('getAllUser', { msg: '查询所有用户' })
    users.value = JSON.parse(result)
  } catch (error) {
    console.error('Error removing user:', error)
  }
}

</script>

<template>
  <div>
    <el-button type="primary" @click="addUser">添加用户</el-button>
    <el-button v-if="!winId" type="primary" @click="gotoPath('/home')">返回</el-button>
    <el-button v-if="winId" type="primary" @click="closeWindow">关闭</el-button>
    <el-table :data="users">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="userPass" label="密码"></el-table-column>
      <el-table-column prop="userSort" label="排序"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="removeUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped lang="stylus"></style>
